package com.xuecheng.learning.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LearningProgressDto;
import com.xuecheng.commons.model.dto.RecordDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.learning.domain.CourseRecord;
import com.xuecheng.learning.mapper.CourseRecordMapper;
import com.xuecheng.learning.service.CourseRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.api.MediaClient;
import com.xuecheng.search.api.SearchApi;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 选课记录 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-08
 */
@Service
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordMapper, CourseRecord> implements CourseRecordService {

    // 查询选课记录
    @Override
    public ResponseResult myCourseRec(Long coursePubId) {
        // 1.获取登录用户id
        Long userId = AuthInfoHolder.getUserId();
        // 2.构建条件
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId, userId);
        qw.eq(CourseRecord::getCoursePubId, coursePubId);
        // 3.查询选课记录
        CourseRecord courseRecord = this.getOne(qw);
        // 判断
        if (ObjectUtil.isEmpty(courseRecord)) {
            return ResponseResult.okResult();
        }
        // 转vo
        CourseRecordVo vo = BeanHelper.copyProperties(courseRecord, CourseRecordVo.class);
        return ResponseResult.okResult(vo);
    }

    @Autowired
    private SearchApi searchApi;

    // （支付成功了）保存或更新选课记录
    @Override
    public ResponseResult saveRecord(RecordDto dto) {
        // 1.查询选课记录
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId, dto.getUserId());
        qw.eq(CourseRecord::getCoursePubId, dto.getCoursePubId());
        CourseRecord courseRecord = this.getOne(qw);
        // 2.之前学生学了几节免费课，这次修改为已支付
        if (ObjectUtil.isNotEmpty(courseRecord)) {
            courseRecord.setPaid(OrdersConstants.PAID);
            this.updateById(courseRecord);
        } else {
            // 3.学生没有试学，直接购买
            courseRecord = new CourseRecord();
            courseRecord.setUserId(dto.getUserId()); // 用户id
            ResponseResult<CoursePubIndexVo> responseResult = searchApi.findById(dto.getCoursePubId().toString());
            if (responseResult.getCode() != 0) {
                throw new BusinessException(ErrorCode.ERROR);
            }
            CoursePubIndexVo indexVo = responseResult.getData();
            courseRecord.setCompanyId(indexVo.getCompanyId()); // 机构id
            courseRecord.setCourseId(indexVo.getCourseId()); // 课程id
            courseRecord.setCoursePubId(indexVo.getCourseId()); // 课程发布id
            courseRecord.setCoursePubName(indexVo.getName()); // 课程名称
            courseRecord.setTeachmode(indexVo.getTeachmode()); // 教育模式
            courseRecord.setCreateDate(DateUtil.date()); // 创建时间
            courseRecord.setPaid(OrdersConstants.PAID); // 已支付
            // 保存数据库
            this.save(courseRecord);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private ContentClient contentClient;

    @Autowired
    private MediaClient mediaClient;

    // 课程详情页查询媒资播放地址
    @Override
    public ResponseResult resourceUrl(Long coursePubId, Long mediaId, Long teachplanId) {
        // 1.查询课程发布是否收费
        ResponseResult<CoursePubVo> pubResponse = contentClient.findById(coursePubId);
        CoursePubVo pubVo = pubResponse.getData();
        String charge = pubVo.getCharge(); // 201000 免费、201001 收费
        // 2.如果课程收费
        if (charge.equals(CourseConstants.CHARGE_YES)) {
            // 在查询课程计划是否收费
            ResponseResult<TeachplanVo> planResponse = contentClient.findTeachplanById(teachplanId);
            TeachplanVo planVo = planResponse.getData();
            String isPreview = planVo.getIsPreview(); // 0 不支持 1支持
            // 3.如果不支持预览，查询用户是否支付
            if (isPreview.equals("0")) {
                // （根据用户id和课程发布id和支付查询选课记录）
                LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
                qw.eq(CourseRecord::getCoursePubId, coursePubId);
                qw.eq(CourseRecord::getUserId, AuthInfoHolder.getUserId());
                qw.eq(CourseRecord::getPaid, 1);
                CourseRecord record = this.getOne(qw);
                // 查询用户是否支付
                if (record==null ) {
                    // 不能播放
                    throw new BusinessException(ErrorCode.NOTPLAY);
                }
            }
        }
        // 4.表示此课程：免费、收费（试看）、已付费，返回媒资播放地址
        ResponseResult<ResourceVo> responseResult = mediaClient.findMedisUrl(mediaId);
        ResourceVo resourceVo = responseResult.getData();
        return ResponseResult.okResult(resourceVo);
    }

    // 免费课程新增选课，或者更新学习进度
    @Override
    public ResponseResult progress(LearningProgressDto dto) {
        // 1.当前用户是否有选课记录
        Long userId = AuthInfoHolder.getUserId();
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId, userId);
        qw.eq(CourseRecord::getCoursePubId, dto.getCoursePubId());
        CourseRecord record = this.getOne(qw);

        // 2.如果有
        if (record!=null) {
            // 更新学习进度（课程计划）
            record.setTeachplanId(dto.getTeachPlanId());
            record.setTeachplanName(dto.getTeachPlanName());
            this.updateById(record);
        }else{
            // 3.如果没有，构建选课记录，保存数据库
            record = new CourseRecord();
            record.setUserId(userId); // 用户id
            ResponseResult<CoursePubIndexVo> responseResult = searchApi.findById(dto.getCoursePubId().toString());
            if (responseResult.getCode() != 0) {
                throw new BusinessException(ErrorCode.ERROR);
            }
            CoursePubIndexVo indexVo = responseResult.getData();
            record.setCompanyId(indexVo.getCompanyId()); // 机构id
            record.setCourseId(indexVo.getCourseId()); // 课程id
            record.setCoursePubId(indexVo.getCourseId()); // 课程发布id
            record.setCoursePubName(indexVo.getName()); // 课程名称
            record.setTeachmode(indexVo.getTeachmode()); // 教育模式
            record.setCreateDate(DateUtil.date()); // 创建时间
            record.setPaid(OrdersConstants.NOT_PAID); // 未支付
            record.setTeachplanId(dto.getTeachPlanId()); // 学习进度
            record.setTeachplanName(dto.getTeachPlanName());
            this.save(record);
        }
        return ResponseResult.okResult();
    }
}
